import request from '@/util/request.js'
import { loginUtil } from '@/Service/login.js'

async function getFullCategories() {
	return (await request.get('/book/category')).data.data;
}

function getCategoriesAndBooks(fullCategories) {
	return {
		categories: getCategories(fullCategories),
		books: getBooks(fullCategories)
	}
}

function getCategories(data) {
	const categories = [];

	function traverse(category) {
		// 添加当前分类
		categories.push(category);

		// 如果有子分类，递归处理
		if (category.children?.length) {
			category.children.forEach(subcategory => traverse(subcategory))
		}
	}

	data.forEach(item => traverse(item));
	return categories;
}

function getBooks(data) {
	let books = [];

	function traverse(item) {
		// 添加当前书籍
		if (item.books) {
			books = books.concat(item.books);
		}

		// 如果有子分类，递归处理
		if (item.children?.length) {
			item.children.forEach(subitem => traverse(subitem))
		}
	}

	data.forEach(item => traverse(item));
	return books;
}

function getAllBooksFromCategory(targetCategory) {
	let books = []
	function traverse(category) {
		if (Array.isArray(category?.books) && category.books.length) {
			books = [...books, category.books]
		}
		if  (Array.isArray(category?.children) && category.children.length) {
			category?.children.forEach(subcategory => traverse(subcategory))
		}
	}
	traverse(targetCategory)
	return books
}

async function getAllBorrowRecords() {
	return (await request.get('/borrowing/record/all')).data;
}

async function borrowBookById(bookId) {
	const requestBody = {
		"userId": loginUtil.getCurrentUserId(),
		"bookId": bookId,
		"borrowTime": formatDate(new Date())
	}
	return (await request.post('/borrowing/borrowBook', requestBody)).data
}

async function returnBookByUserBookId(borrowId) {
	return (await request.put('/borrowing/returnBook', {
		borrowId,
		returnTime: formatDate(new Date())
	})).data
}

function formatDate(date, format = 'yyyy-MM-dd HH:mm:ss') {
	const pad = (num) => num.toString().padStart(2, '0');
	return format
		.replace(/yyyy/g, date.getFullYear())
		.replace(/MM/g, pad(date.getMonth() + 1))
		.replace(/dd/g, pad(date.getDate()))
		.replace(/HH/g, pad(date.getHours()))
		.replace(/mm/g, pad(date.getMinutes()))
		.replace(/ss/g, pad(date.getSeconds()));
}

const operation = {
	borrowBookById,
	returnBookByUserBookId
}

export {
	getFullCategories,
	getCategoriesAndBooks,
	getAllBooksFromCategory,
	getAllBorrowRecords,
	operation
}